package com.yvon.maple.service.auth.valicode.validate.code.repository;


import com.yvon.boot.redis.service.RedisService;
import com.yvon.maple.constants.RedisKey;
import com.yvon.maple.service.auth.valicode.vo.CodeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.yvon.maple.constants.RedisKey.Auth.CODE_VALID;


/**
 * 基于redis的验证码存取器
 * @author : Yvon
 * @since 2019/5/26
 */
@Component
@Slf4j
public class RedisCodeRepository implements CodeRepository {

	@Autowired
	private RedisService redisService;

	/**
	 * 保存验证码
	 *
	 * @param code
	 * @author : Yvon / 2021-08-25
	 */
	@Override
	public void save(CodeVo code) {
		redisService.set(buildKey(code.getGrantType(), code.getKey()), code, code.getExpire() + 60);
	}


	/**
	 * 获取验证码
	 *
	 * @param key 关键
	 * @return {@link CodeVo }
	 * @author : Yvon / 2021-08-24
	 */
	@Override
	public CodeVo get(String grantType, String key) {

		Object value = redisService.get(buildKey(grantType, key));
		if (value == null) {
			return null;
		}
		return (CodeVo) value;
	}

	/**
	 * Remove.
	 *
	 * @param key 关键
	 * @author : Yvon / 2021-08-24
	 */
	@Override
	public void remove(String grantType, String key) {
		redisService.del(buildKey(grantType, key));
	}

	private String buildKey(String grantType, String key ) {
		return CODE_VALID +grantType +":" + key;
	}

}
